package edu.zju.udms.dnavigator.core.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

public class EntitySearchServlet extends NavigatorServlet{
	
	private final static Logger logger=Logger.getLogger(EntitySearchServlet.class);
	
	private static final long serialVersionUID = 7491411846034308654L;

	private static final String[] KeywordSearchFields={"name","qualifiedName","type","source","owner","bussinessName","description","_fulltext"};
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/*TODO 
		 * 1. 暂时想不到比较好的过滤和多字段搜索的方式,过滤的逻辑有点问题
		 * 2. 分页以后做
		 * */ 
		boolean matchAll=true;
		BooleanQuery boolQuery=new BooleanQuery();
		String[] path = req.getPathInfo().split("/");
		if(path.length>1){
			matchAll=false;
			String keyword = path[1];
			for(String field:KeywordSearchFields){
				boolQuery.add(new TermQuery(new Term(field,keyword)), BooleanClause.Occur.SHOULD);
			}
		}
		Map<String, String[]> map = req.getParameterMap();
		for(Entry<String, String[]> entry:map.entrySet()){
			matchAll=false;
			String condition = entry.getKey();
			String[] values=entry.getValue();
			for(String value:values){
				boolQuery.add(new TermQuery(new Term(condition,value)), BooleanClause.Occur.MUST);
			}
		}
		Query query=matchAll?new MatchAllDocsQuery():boolQuery;
		logger.debug("query"+query.toString());
		List<Map<String, String>> entities = repository.searchMap(query, 1000);
		Map<String,Integer> sourceMap=new HashMap<>(),typeMap=new HashMap<>();
		for(Map<String, String> e:entities){
			String source=e.get("source");
			String type=e.get("type");
			sourceMap.put(source, sourceMap.containsKey(source)?(sourceMap.get(source)+1):1);
			typeMap.put(type, typeMap.containsKey(type)?(typeMap.get(type)+1):1);
		}
		resp.setCharacterEncoding("UTF-8");
		PrintWriter writer = resp.getWriter();
		JSONObject result=new JSONObject();
		JSONObject filter=new JSONObject();
		filter.put("source", sourceMap);
		filter.put("type", typeMap);
		result.put("data", JSONArray.fromObject(entities));
		result.put("filter", filter);
		writer.write(result.toString());
	}
}
